'''
Created on 18 Mar 2010
@author: iliask
'''
from __future__ import division
__version__ = '0.0.1'
__author__ = 'iliask'

from ftplib import FTP
import sys
import os

class FtpDownload(FTP):
    def __init__(self, host, user, passwd):
        self.__isconnected = False
        self.__asciifiles = ['csv', 'txt','c', 'java', 'cpp', 'sh', 'f', 'f90', 'f77', 'f95', 'bas"', 'pro', 'csh', 'ksh', 'conf', 'htm', 'html', 'php', 'pl', 'cgi', 'inf', 'js', 'asp', 'bat', 'cfm', 'css', 'dhtml', 'diz', 'h', 'hpp', 'ini', 'mak', 'nfo', 'shtml', 'shtm', 'tc','cls','vbw','mod']
        try:
            sys.stderr.write('Connecting to {0} using account \'{1}\'\n'.format(host, user))
            FTP.__init__(self, host, user, passwd)
            self.__isconnected = True
        except Exception, e:
            print e        
    def handleDownload(self, block):
        print ".",
    def getRemoteFiles(self, direremote, dirlocal):
        class LocalWriter:
            def __init__(self, file, remotesize):
                self.f = open(file, "w")
                self.__maxoutlen = 0
                self.__remotesize = remotesize
                self.__fpath = os.path.split(self.f.name)[0]
                self.__fname = os.path.split(self.f.name)[1]
            def __del__(self):
                sys.stderr.write(' '*self.__maxoutlen + '\r')
                sys.stderr.write('{0} [{1}]\n'.format(self.f.name,
                                                      self.getLocalSizeFormated()))
                self.f.close()
            def __call__(self, data):
                self.f.write(data)
                self.f.write('\n')
                s = 'Transferring {0}: [{1}] {2:.2f}%\r'.format(self.__fname,
                                                                self.getLocalSizeFormated(),
                                                                self.getTransferProgress())
                if len(s) > self.__maxoutlen:
                    self.__maxoutlen = len(s)
                sys.stderr.write(s)
            def getLocalSize(self):
                return os.path.getsize(self.f.name)
            def getTransferProgress(self):
                return round(100 * self.getLocalSize() / self.__remotesize,2)
            def getLocalSizeFormated(self):
                mb=1024 ** 2
                if os.path.getsize(self.f.name) / mb > 1:
                    return '{0:.3f}Mb'.format(os.path.getsize(self.f.name) / mb)
                else:
                    kb=1024
                    return '{0:.2f}Kb'.format(os.path.getsize(self.f.name) / kb)
                
        FTP.cwd(self, direremote)
        rFileSet = FTP.nlst(self)
        for f in rFileSet:
            localFile = os.path.join(dirlocal, f)
            fileObj = LocalWriter(localFile, FTP.size(self, f))
            sys.stderr.write('Getting {0}\r'.format(f))
            ext = os.path.splitext(f)[1].replace('.', '')
            if ext in self.__asciifiles:
                FTP.retrlines(self, 'RETR ' + f, fileObj)
            else:
                FTP.retrbinary(self, 'RETR ' + f, fileObj)
if __name__ == '__main__':
    d = FtpDownload(host='207.5.70.144', user='ciusers', passwd='citest')
    d.getRemoteFiles('/ciusers/1002/Home/815', 'Z:\\TEMP')
